package com.campus.mapper;


import com.campus.domain.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    /**
     * 验证用户名是否已被被人占用
     */
    @Select("select count(*) from sys_user where user_name = #{username}")
    Long count(String username);
    /**
     * 保存用户
     */
    @Options(useGeneratedKeys=true,keyProperty ="id")
    @Insert("insert into sys_user(user_name,password,avatar,create_time,update_time) values(#{userName},#{password},#{avatar},#{createTime},#{updateTime})")
    void save(User user);
    /**
     * 根据用户名查询用户信息
     */
    @Select("select * from sys_user where user_name = #{username}")
    User selectByUserName(String userName);

    /**
     * 获取用户信息
     */
    @Select("select * from sys_user where id = #{userId}")
    User findById(Long userId);
    /**
     * 查询用户按钮权限
     */
    @Select("select button from permission where user_id = #{id}")
    List<String> getButtonPermission(Long id);
    
    /**
     * 更新用户信息
     */
    @Update("update sys_user set avatar = #{avatar},email = #{email}, phone = #{phone}, update_time = #{updateTime} where id = #{id}")
    void updateUserInfo(User user);
    
    /**
     * 查询用户列表（分页）
     */
    @Select("<script>" +
            "select * from sys_user " +
            "<where>" +
            "  <if test='username != null and username != \"\"'>" +
            "    and user_name like concat('%', #{username}, '%')" +
            "  </if>" +
            "</where>" +
            "order by create_time desc " +
            "limit #{offset}, #{size}" +
            "</script>")
    List<User> selectUserList(@Param("username") String username, 
                              @Param("offset") Integer offset, 
                              @Param("size") Integer size);
    
    /**
     * 统计用户总数
     */
    @Select("<script>" +
            "select count(*) from sys_user " +
            "<where>" +
            "  <if test='username != null and username != \"\"'>" +
            "    and user_name like concat('%', #{username}, '%')" +
            "  </if>" +
            "</where>" +
            "</script>")
    Long countUserTotal(@Param("username") String username);
    
    /**
     * 更新用户（管理员）
     */
    @Update("update sys_user set email = #{email}, phone = #{phone}, user_type = #{userType}, update_time = #{updateTime} where id = #{id}")
    void updateUser(User user);
    
    /**
     * 删除用户
     */
    @Delete("delete from sys_user where id = #{id}")
    void deleteById(@Param("id") Long id);
}
